<template>
  <div class="search-list-container searchHeight">
    <div class="search-wrapper">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="auto"
      >
        <el-form-item label="请选择IP段地址" prop="ipAddress">
          <el-select v-model="queryParams.ipAddress" filterable  placeholder="请选择">
            <el-option
              v-for="item in ipSelectList"
              :key="item.id"
              :label="item.ipAddress"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请输入IP段地址" prop="ipHandAddress">
          <el-input
            v-model="queryParams.ipHandAddress"
            placeholder="请输入IP段地址"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          class="search-icon"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form>
    </div>
    <div class="list-wrapper">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
           
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete({})"
          
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click="batchImport"
            v-hasPermi="['system:registration:edit']"
            >批量导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:registration:export']"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        ref="tables"
        width="100%"
        height="100%"
        v-loading="loading"
        :data="ipAddressList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="IP段地址" align="center" prop="ipAddress">
        </el-table-column>
        <el-table-column
          label="新增时间"
          align="center"
          prop="createTime"
          width="250"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="IP容量" align="center" prop="ipSize">
        </el-table-column>
        <el-table-column
          label="办公地区"
          align="center"
          prop="addressToString"
        />
        <el-table-column
          label="业务类型"
          align="center"
          prop="businessTypeToString"
          width="100"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="单位"
          align="center"
          prop="unit"
          width="100"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="状态"
          align="center"
          prop="statusToString"
          width="100"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span
              :style="{ color: scope.row.status == 0 ? '#F9BE71' : '#A2D05C' }"
              >{{ scope.row.statusToString }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-data"
              v-if="scope.row.status == 0 && !scope.row.unit"
              @click="allocationUnit(scope.row)"
              v-hasPermi="['alarm:deviceRule:edit']"
              >分配单位</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-notebook-2"
              v-if="scope.row.status == 0 &&!scope.row.unit&&scope.row.ipSize!=1"
              @click="splitNetworkSegments(scope.row, scope.index)"
              v-hasPermi="['monitor:operlog:query']"
              >拆分网段</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status == 0 && !scope.row.unit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['alarm:deviceRule:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              v-if="scope.row.unit"
              @click="recovery(scope.row)"
              v-hasPermi="['alarm:deviceRule:edit']"
              >回收</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-check"
              v-if="scope.row.status == 0 && scope.row.unit"
              @click="operateIPStatus(scope.row)"
              v-hasPermi="['alarm:deviceRule:edit']"
              >启用</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-close"
              v-if="scope.row.status == 1 && scope.row.unit"
              @click="operateIPStatus(scope.row)"
              v-hasPermi="['alarm:deviceRule:edit']"
              >停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getIPAddressList"
      />
    </div>
    <!-- 新增网段 -->
    <operate-segment
      :showDialog.sync="showAddSegmentDialog"
      :isAdd="isAdd"
      :detail="detail"
      v-if="showAddSegmentDialog"
      @updateList="getIPAddressList"
    ></operate-segment>
    <!-- 拆分网段 -->
    <split-network-segments
      :detail="detail"
      :showDialog.sync="showSplitSegmentDialog"
      v-if="showSplitSegmentDialog"
      @updateList="getIPAddressList"
    ></split-network-segments>
    <!-- 分配单位 -->
    <allocation-unit
      :showDialog.sync="showUnitDialog"
      :id="detail.id"
      @updateList="getIPAddressList"
    ></allocation-unit>
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="3"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
      >
        <div>1.若无批量导入模板，请先点击【导入模板】进行下载。</div>
        <el-button
          size="small"
          type="primary"
          @click.stop.prevent="importTemplate()"
          >导入模板</el-button
        >
        <div>2.点击【选择文件】,选择按模板填写完成的文件进行导入。</div>
        <el-button size="small" type="primary">选择文件</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OperateSegment from "./operateSegment";
import SplitNetworkSegments from "./splitNetworkSegments";
import AllocationUnit from "./allocationUnit";
import {
  getIPAddressList,
  recovery,
  operateIPStatus,
  deleteIP,
  getSelectIPList,
} from "@/api/businessSupport/businessManagement.js";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      ipAddressList: [],
      loading: false,
      addressList: [
        {
          value: 1,
          label: 1,
        },
      ],
      showAddSegmentDialog: false,
      showSplitSegmentDialog: false,
      showUnitDialog: false,
      isAdd: true,
      detail: {},
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ipAddress/import",
      },
      multiple: true,
      ids: "",
      ipSelectList: [],
    };
  },
  components: {
    OperateSegment,
    SplitNetworkSegments,
    AllocationUnit,
  },
  methods: {
    async getSelectIPList() {
      const result = await getSelectIPList();
      this.ipSelectList = result.data;
    },
    // 删除按钮操作
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除所选的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteIP(ids);
        })
        .then(() => {
          this.getIPAddressList();
          this.$message({
            type: "success",
            message: result.msg,
          });
        })
        .catch(() => {});
    },
    allocationUnit(row) {
      this.detail = row;
      this.showUnitDialog = true;
    },
    handleQuery() {
      this.getIPAddressList();
    },
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.queryParams.pageSize = 10;
      this.queryParams.pageNum = 1;
      this.getIPAddressList();
    },
    handleAdd() {
      this.isAdd = true;
      this.showAddSegmentDialog = true;
    },
    handleUpdate(row) {
      this.isAdd = false;
      this.detail = row;
      this.showAddSegmentDialog = true;
    },
    splitNetworkSegments(row) {
      this.detail = row;
      this.showSplitSegmentDialog = true;
    },
    async getIPAddressList() {
      this.loading = true;
      const result = await getIPAddressList(this.queryParams);
      this.loading = false;
      this.ipAddressList = result.data.records;
      this.total = result.data.total;
    },
    // 回收
    async recovery(row) {
      const result = await recovery(row.id);
      this.getIPAddressList();
      this.$message({
        type: "success",
        message: result.msg,
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/portal/ipAddress/export",
        {
          ...this.queryParams,
        },
        `IP地址列表_${new Date().getTime()}.xlsx`
      );
    },
    async operateIPStatus(row) {
      const result = await operateIPStatus({
        id: row.id,
        status: row.status,
      });
      this.getIPAddressList();
      this.$message({
        type: "success",
        message: result.msg,
      });
    },
    // 批量导入
    batchImport() {
      this.upload.open = true;
    },
    // 下载模板操作
    importTemplate() {
      this.download("/portal/ipAddress/importTemplate", {}, `导入模板.xlsx`);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getIPAddressList();
      if (response.code == 5000) {
        this.download(
          "/portal/ipAddress/exportError",
          {},
          `导入失败的数据.xlsx`
        );
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
  },
  mounted() {
    this.getIPAddressList();
    this.getSelectIPList();
  },
};
</script>

<style lang="scss" scoped>
.searchHeight {
  height: calc(100% - 54px) !important;
}
.search-icon {
  margin-left: 30px !important;
}
::v-deep .el-upload {
  text-align: left;
}
::v-deep .el-upload div {
  margin: 10px 0;
}
</style>